from django.shortcuts import render
# Create your views here.
from django_redis import get_redis_connection
from rest_framework.generics import ListCreateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from apps.spit.models import Spit
from apps.spit.serializer import SpitModelSerializer


# 吐槽列表
class SpltListView(ListCreateAPIView):
    pagination_class = None
    def perform_authentication(self, request):
        pass

    def get_queryset(self):

        # 获取数据进行倒序排序
        querysets = Spit.objects.filter(parent=None).order_by("-publishtime")
        # 准备空列表
        spitlist = []
        try:
            user = self.request.user
        except Exception:
            user = None
        # 如果用户登录查询用户是否点赞或收藏
        if user is not None and user.is_authenticated:
            # 链接redis数据库
            redis_conn = get_redis_connection('spit')
            for splt in querysets:
                hasthumbup = redis_conn.hget('%s_%s' % (user.id, id), 'hasthumbup')
                collected = redis_conn.hget('%s_%s' % (user.id, id), 'collected')
                # 如果用户收藏或点赞字段修改为True
                if hasthumbup:
                    splt.hasthumbup = True
                if collected:
                    splt.collected = True
                spitlist.append(splt)
        else:
            spitlist = querysets

        return spitlist
    # 序列化
    serializer_class = SpitModelSerializer

# 收藏或取消收藏
class CollectView(APIView):

    permission_classes = [IsAuthenticated]
    def put(self, request, id):
        try:
            user = request.user
        except Exception:
            user = None

        queryset = Spit.objects.get(id=id)

        if user is not None and user.is_authenticated:
            redis_conn = get_redis_connection('spit')
            result = redis_conn.hget('%s_%s' % (user.id, id), 'collected')
            if result:
                redis_conn.hdel('%s_%s' % (user.id, id), 'collected')
                queryset.collected = False
                queryset.save()
                return Response({'success': 'true', 'message': '取消收藏成功'})
            else:
                redis_conn.hset('%s_%s' % (user.id, id), 'collected', 1)
                queryset.collected = True
                queryset.save()
                return Response({"success": 'true', "message": "收藏成功"})
        else:
            return Response({'success': 'false', 'message': '未登录'}, status=400)



  #吐槽详情页
class SpltDetailsView(APIView):
    def get(self, request, id):
        queryset = Spit.objects.get(id=id)
        try:
            user = self.request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            redis_conn = get_redis_connection('spit')

            hasthumbup = redis_conn.hget('%s_%s' % (user.id, id), 'hasthumbup')
            collected = redis_conn.hget('%s_%s' % (user.id, id), 'collected')
            if hasthumbup:
                queryset.hasthumbup = True
            if collected:
                queryset.collected = True
        serializer = SpitModelSerializer(queryset)
        return Response(serializer.data)



# 点赞或者取消点赞
class UpdateThumbupView(APIView):

    def perform_authentication(self, request):
        pass

    def put(self, request, id):

        try:
            user = request.user
        except Exception:
            user = None

        queryset = Spit.objects.get(id=id)
        thumbup = queryset.thumbup
        if user is not None and user.is_authenticated:
            redis_conn = get_redis_connection('spit')
            result = redis_conn.hget('%s_%s' % (user.id, id), 'hasthumbup')
            if result:
                queryset.thumbup = thumbup - 1
                queryset.save()
                redis_conn.hdel('%s_%s' % (user.id, id), 'hasthumbup')
                return Response({'success': 'true', 'message': '取消点赞成功'})
            else:
                redis_conn.hset('%s_%s' % (user.id, id), 'hasthumbup', 1)
                queryset.thumbup = thumbup + 1
                queryset.save()
                return Response({"success": 'true', "message": "点赞成功"})
        else:
            return Response({'success': 'false', 'message': '未登录'}, status=400)

 # 获取吐槽评论
class GetSpltCommentView(APIView):
    def get(self, request, id):
        splts = Spit.objects.filter(parent=id).order_by('-publishtime')
        spltlist = []

        try:
            user = request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            redis_conn = get_redis_connection('spit')
            for splt in splts:
                hasthumbup = redis_conn.hget('%s_%s' % (user.id, id), 'hasthumbup')
                collected = redis_conn.hget('%s_%s' % (user.id, id), 'collected')
                if hasthumbup:
                    splt.hasthumbup = True
                if collected:
                    splt.collected = True
                spltlist.append(splt)
        else:
            spltlist = splts

        serializer = SpitModelSerializer(spltlist, many=True)
        return Response(serializer.data)



